﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;  

//闹钟订阅器
public class AlarmPublisher
{
    private readonly List<Alarm> _alarms = new();  //闹钟列表
    private readonly System.Timers.Timer _alarmCheckTimer;   //响铃时间
    private readonly System.Timers.Timer _tickTimer;    //滴答时间
    private bool _isTickEnabled;     //是否滴答
    // debug：需要明确使用 System.Timers.Timer，不能只写Timer以免与其他命名空间中的Timer冲突

    public event EventHandler<TickEventArgs> Tick;    //滴答事件
    public event EventHandler<AlarmEventArgs> AlarmTriggered;        //响铃事件

    public AlarmPublisher()       //闹钟订阅器
    {
        _alarmCheckTimer = new System.Timers.Timer(1000) { AutoReset = true };  //响铃
        _alarmCheckTimer.Elapsed += CheckAlarms;
        _alarmCheckTimer.Start();

        _tickTimer = new System.Timers.Timer(5000) { AutoReset = true };     //滴答
        _tickTimer.Elapsed += (s, e) => Tick?.Invoke(this, new TickEventArgs { CurrentTime = DateTime.Now });
        UpdateTickState();
    }

    public void EnableTick(bool enable)    //判断是否滴答
    {
        _isTickEnabled = enable;
        UpdateTickState();
    }

    private void UpdateTickState() => _tickTimer.Enabled = _isTickEnabled;    //更新滴答的状态

    private void CheckAlarms(object sender, ElapsedEventArgs e)    //响铃
    {
        foreach (var alarm in _alarms.ToArray())    //逐一比照闹钟列表判断是否响铃
        {
            if (alarm.ShouldTrigger(DateTime.Now))
            {
                AlarmTriggered?.Invoke(this, new AlarmEventArgs      //激活事件
                {
                    TriggerTime = DateTime.Now,
                    Sound = alarm.Sound,
                    TriggeredAlarm = alarm
                });

                if (alarm.Mode == RepeatMode.Once) alarm.IsActive = false;    //如果不重复则关闭闹钟
            }
        }
    }

    public void AddAlarm(Alarm alarm) => _alarms.Add(alarm);     //添加闹钟
    public void RemoveAlarm(Alarm alarm) => _alarms.Remove(alarm);   //移除闹钟
    public IEnumerable<Alarm> GetAlarms() => _alarms.AsReadOnly();    //闹钟列表设置为只读模式
}

public class TickEventArgs : EventArgs     //滴答事件
{
    public DateTime CurrentTime { get; set; }
}

public class AlarmEventArgs : EventArgs    //响铃事件
{
    public DateTime TriggerTime { get; set; }     //响铃时间
    public string Sound { get; set; }    //铃声
    public Alarm TriggeredAlarm { get; set; }      //所激活的闹钟
}
